package cn.monkey.family.data;

import java.util.function.Function;

public interface Results {

    static <T> Result<T> result(int code, String msg, T data) {
        return Result.<T>builder().code(code).msg(msg).data(data).build();
    }

    static <T> Result<T> ok(T data) {
        return Result.<T>builder().code(ResultCode.OK).data(data).build();
    }

    Result<Object> EMPTY = Result.builder().code(ResultCode.OK).build();

    @SuppressWarnings("unchecked")
    static <T> Result<T> ok() {
        return (Result<T>) EMPTY;
    }

    static <T> Result<T> error(Throwable throwable) {
        return Result.<T>builder().code(ResultCode.ERROR).msg(throwable.getMessage()).build();
    }

    static <T> Result<T> fail(int code, String msg) {
        return Result.<T>builder().code(code).msg(msg).build();
    }

    static <T> Result<T> fail(String msg) {
        return fail(ResultCode.FAIL, msg);
    }

    static <R, T> Result<R> map(Result<T> result, Function<T, R> mapper) {
        return result.map(mapper);
    }

    static <V> Result<V> notFound() {
        return Result.<V>builder().code(ResultCode.NOT_FOUND).build();
    }

    static <V, T> Result<V> fromFailOrError(Result<T> result) {
        return result(result.getCode(), result.getMsg(), null);
    }

    static boolean isOk(Result<?> result) {
        return result != null && result.getCode() == ResultCode.OK;
    }
}
